<template>
  <div>
    <div class="search-box">
      <transition name="el-zoom-in-top">
        <el-form :inline="true"  class="search-form search-fiexd" size="medium" label-width="100px" v-show="showForm">
          <el-form-item label="所属信息：">
            <el-select v-model="store.params.marketId" placeholder="请选择市场" filterable>
              <el-option v-for="(item,index) in store.marketOptions" :key="item.marketId" :label="item.marketName" :value="item.marketId"></el-option>
            </el-select>
            <el-select v-model="store.params.shopId" placeholder="请选择店铺" clearable filterable>
              <el-option v-for="(item,index) in store.shopOptions" :key="item.shopId"  :label="item.shopName" :value="item.shopId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="基本信息：">
            <el-select clearable v-model="store.params.brandId" placeholder="请选择品牌" filterable>
              <el-option-group v-for="group in store.brandOptions" :key="group.initial" :label="group.initial">
                <el-option v-for="item in group.brandInfo" :key="item.brandId" :label="`${group.initial} - ${item.brandName}`" :value="item.brandId">
                </el-option>
              </el-option-group>
            </el-select>
            <el-select v-model="store.params.seriesId" placeholder="请选择车系" clearable filterable>
              <el-option v-for="(item,index) in store.seriesOptions" :key="item.seriesId"  :label="item.seriesName" :value="item.seriesId"></el-option>
            </el-select>
            <el-select v-model="store.params.modelId" placeholder="请选择车型" clearable filterable>
              <el-option v-for="(item,index) in store.modeOptions" :key="item.modelId"  :label="item.modelName" :value="item.modelId"></el-option>
            </el-select>
            <el-select v-model="store.retailPrice" placeholder="请选择零售价" clearable>
              <el-option label="0-5万" value="1"></el-option>
              <el-option label="5-10万" value="2"></el-option>
              <el-option label="10-20万" value="3"></el-option>
              <el-option label="20-30万" value="4"></el-option>
              <el-option label="30-50万" value="5"></el-option>
              <el-option label="50-100万" value="6"></el-option>
              <el-option label="100万以上" value="7"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="车辆状态：">
            <el-select v-model="store.params.carStockState" placeholder="请选择库存状态" clearable>
              <el-option label="未入库" value="0"></el-option>
              <el-option label="已驳回" value="1"></el-option>
              <el-option label="已撤销" value="2"></el-option>
              <el-option label="入库中" value="10"></el-option>
              <el-option label="已入库" value="20"></el-option>
              <el-option label="已出库" value="40"></el-option>
            </el-select>
            <el-select v-model="store.params.carDetectState" placeholder="请选择检测状态" clearable>
              <el-option label="未初检" value="500"></el-option>
              <el-option label="初检不通过" value="510"></el-option>
              <el-option label="初检通过" value="520"></el-option>
              <el-option label="申请复检中" value="530"></el-option>
              <el-option label="复检完成" value="540"></el-option>
            </el-select>
            <el-select v-model="store.params.carSaleState" placeholder="请选择上架状态" clearable>
              <el-option label="未上架" value="0"></el-option>
              <el-option label="已上架" value="20"></el-option>
              <el-option label="已下架" value="30"></el-option>
            </el-select>
            <el-select v-model="store.params.carOrderState" placeholder="请选择预定状态" clearable>
              <el-option label="未预定" value="0"></el-option>
              <el-option label="已预定" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label=" ">
            <el-select v-model="store.params.carPledgeState" placeholder="请选择抵押状态" clearable>
              <el-option label="未抵押" value="300"></el-option>
              <el-option label="已抵押" value="310"></el-option>
            </el-select>
            <el-select v-model="store.params.carAuthState" placeholder="请选择认证状态" clearable>
              <el-option label="未认证" value="0"></el-option>
              <el-option label="已认证" value="10"></el-option>
            </el-select>
            <el-select v-model="store.params.carSiteState" placeholder="请选择在场状态" clearable>
              <el-option label="未入场" value="400"></el-option>
              <el-option label="已入场" value="410"></el-option>
              <el-option label="出场审核中" value="420"></el-option>
              <el-option label="出场审核通过" value="430"></el-option>
              <el-option label="已出场" value="440"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="更多信息：">
            <el-select v-model="store.params.carTypeId" placeholder="请选择车身类型" clearable>
              <el-option v-for="(item,index) in $store.state.common.carBaseParamOptions.baseCarTypeOptions" :key="item.carTypeId"  :label="item.carTypeName" :value="item.carTypeId"></el-option>
            </el-select>
            <el-select v-model="store.carAge" placeholder="请选择车龄" clearable>
              <el-option label="1年内" value="1"></el-option>
              <el-option label="1-3年" value="2"></el-option>
              <el-option label="3-5年" value="3"></el-option>
              <el-option label="5-8年" value="4"></el-option>
              <el-option label="8-10年" value="5"></el-option>
              <el-option label="10年以上" value="6"></el-option>
            </el-select>
            <el-select v-model="store.mileage" placeholder="请选择里程" clearable>
              <el-option label="1万公里内" value="1"></el-option>
              <el-option label="3万公里内" value="2"></el-option>
              <el-option label="6万公里内" value="3"></el-option>
              <el-option label="10万公里内" value="4"></el-option>
              <el-option label="10万公里以上" value="5"></el-option>
            </el-select>
            <el-select v-model="store.params.carEnviron" placeholder="请选择环保标准" clearable>
              <el-option label="国I" value="国I"></el-option>
              <el-option label="国II" value="国II"></el-option>
              <el-option label="国III" value="国III"></el-option>
              <el-option label="国IV" value="国IV"></el-option>
              <el-option label="国V" value="国V"></el-option>
              <el-option label="欧I" value="欧I"></el-option>
              <el-option label="欧II" value="欧II"></el-option>
              <el-option label="欧III" value="欧III"></el-option>
              <el-option label="欧IV" value="欧IV"></el-option>
              <el-option label="欧V" value="欧V"></el-option>
              <el-option label="欧VI" value="欧VI"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="精准查询：">
            <el-input v-model="store.params.carVin" placeholder="vin码" style="width:193px" clearable></el-input>
            <el-input v-model="store.params.carRfid" placeholder="RFID" style="width:193px" clearable></el-input>
          </el-form-item>
          <el-form-item style="float:right;padding-right:10px;">
            <el-button type="primary" icon="el-icon-search" @click="searchCarList">查询</el-button>
            <el-button icon="el-icon-refresh" @click="resetForm('searchForm')">重置</el-button>
            <el-button @click="showForm = !showForm">隐藏</el-button>
          </el-form-item>

        </el-form>
      </transition>
    </div>
    <el-table  style="width: 100%" :data="carList" border v-loading="loading">
      <el-table-column label="首图" prop="carTitle" align="center" width="170" >
        <template slot-scope="scope" style="position:relative"   >
          <div class="a-link" @click="turnToCarDetial(scope.row.carId)">
            <img :src="imgUrl+scope.row.carImageUrl+'.r_300xh_200'" class="car-image" onerror="javascript:this.src='static/images/default.svg'"  >
            <span v-if="scope.row.carAuthState == 10" class="car-auth">
							<img src="static/images/mark.png" alt="" />
						</span>
            <div class="car-state" v-if="scope.row.carBargainPriceState"><em style="background: #FF6816;">特卖</em></div>
            <div class="car-state" v-if="scope.row.carOrderState==1"><em>已预定</em></div>
            <div class="car-state" v-if="scope.row.carPledgeState == 310"><em style="background: #f56e6d;">抵押中</em></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="车辆信息" min-width="280">
        <template slot-scope="scope">
          <h1 class="a-link"  @click="turnToCarDetial(scope.row.carId)">{{scope.row.carTitle || '暂无标题'}}</h1>
          <p>车架号：{{scope.row.carVin}}</p>
          <p>所属市场：{{scope.row.market.marketName }}</p>
          <p class="color-span">
            <span class="color1" v-if="scope.row.carLicenceState == 1">{{scope.row.carLicenceDate | filterDateForDay}}</span>
            <span class="color1" v-if="scope.row.carLicenceState == 2">未上牌</span>
            <span class="color1" v-if="scope.row.carLicenceState == 3">新车</span>
            <span class="color2" v-if="scope.row.carMileage && scope.row.carMileage != 0">{{scope.row.carMileage}}万公里</span>
            <span class="color3" v-if="scope.row.carDisplacement">{{scope.row.carDisplacement || '-'}}{{scope.row.carInletModel || '-'}}</span>
            <span class="color4">{{scope.row.carOutColor}}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column label="零售价" align="center" width="120">
        <template  slot-scope="scope">
          <p>{{scope.row.carRetailPrice | filterPrice}}</p>
        </template>
      </el-table-column>
      <el-table-column label="联系人信息" min-width="180">
        <template  slot-scope="scope">
          <p>联系人：{{scope.row.shop.shopManageName}}</p>
          <p>电话：{{scope.row.shop.shopManageMobile}}</p>
        </template>
      </el-table-column>
      <!-- <el-table-column label="所属区域" prop="region.regionName" align="center"></el-table-column> -->
      <el-table-column label="车辆状态"  align="center" width="170">
        <template slot-scope="scope">
          <p v-if="scope.row.carStockState != 20"><el-tag :type="scope.row.carStockState == 20?'success':'info'" size="mini">{{scope.row.carStockState | filterCarStockState}}</el-tag></p>
          <p v-if="scope.row.carStockState == 20"><el-tag :type="scope.row.carSaleState == 20?'success':'info'" size="mini">{{scope.row.carSaleState | filterCarSaleState }}</el-tag></p>
          <p><el-tag :type="scope.row.carDetectState>=520?'success':'info'" size="mini">{{scope.row.carDetectState | filterCarDetectState }}</el-tag></p>
          <p><el-tag :type="scope.row.carSiteState>=440?'danger':'info'" size="mini"><span v-if="scope.row.carSiteState == 440">{{scope.row.carSiteTime | filterDateForSec}}</span>{{scope.row.carSiteState | filterCarSiteState }}</el-tag></p>
          <p v-if="scope.row.carSiteStatus == 1" ><el-tag type="danger" size="mini">该车已出场5个小时以上！</el-tag></p>

          <p v-if="scope.row.carRfid"><el-tag type="success" size="mini">RFID:{{scope.row.carRfid}}</el-tag></p>
          <p v-else=""><el-tag type="danger" size="mini">RFID未绑定</el-tag></p>

        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template   slot-scope="scope">
          <el-button type="primary" size="mini"  @click.native="turnToCarDetial(scope.row.carId)">查看</el-button>
					<el-dropdown trigger="click">
						<el-button size="mini">
							更多操作<i class="el-icon-arrow-down el-icon--right"></i>
						</el-button>
						<el-dropdown-menu slot="dropdown">

								<el-dropdown-item @click.native="turnToEditCar(scope.row.carId)">编辑车辆</el-dropdown-item>
								<!-- 未完成入库才可删除 -->
              <div v-if="userRoleRight.deleteCar">
                <el-dropdown-item @click.native="carDelete(scope.row.carId, scope.$index)" v-if="scope.row.carStockState < 10">车辆删除</el-dropdown-item>
              </div>
								<!-- 为预定的车辆才可显示 -->
              <div v-if="userRoleRight.carBook">
                <router-link :to="{path: `/car/carOrderAdd/${scope.row.carId}`}" v-if="scope.row.carOrderState != 1"><el-dropdown-item>车辆预定</el-dropdown-item></router-link>
              </div>
								<!-- 初见通过才可申请复检 -->
              <div v-if="userRoleRight.reCheck">
                <el-dropdown-item @click.native="reexamination(scope.row.carId, scope.row)" v-if="scope.row.carDetectState == 520" >申请复检</el-dropdown-item>
              </div>
								<!-- 未完成、驳回、撤销车辆显示 -->
              <div v-if="userRoleRight.applyInStock">
								<router-link :to="{path: `/car/carInStock/${scope.row.carId}`}" v-if="scope.row.carStockState < 10"><el-dropdown-item>申请入库</el-dropdown-item></router-link>
              </div>
                <!-- 在库车辆才可上架下架 -->
              <div v-if="userRoleRight.CarGrounding">
								<el-dropdown-item @click.native="carSaleState20(scope.row.carId, scope.row)" v-if="scope.row.carStockState == 20 && scope.row.carSaleState != 20" >车辆上架</el-dropdown-item>
              </div>
              <div v-if="userRoleRight.CarUnShelve">
                <el-dropdown-item @click.native="carSaleState30(scope.row.carId, scope.row)" v-if="scope.row.carStockState == 20 && scope.row.carSaleState == 20">车辆下架</el-dropdown-item>
              </div>
                <!-- 在库车辆且未销售出库的才显示 -->
              <div v-if="userRoleRight.saleOutStock">
								<router-link :to="{path: `/car/carSaleAdd/${scope.row.carId}`}" v-if="scope.row.carStockState > 10 && scope.row.carStockState != 40"><el-dropdown-item>销售出库</el-dropdown-item></router-link>
              </div>
								<!-- 已预定的车辆才可显示 -->
              <div v-if="userRoleRight.bookDetail">
								<router-link :to="{path: `/car/carOrder/${scope.row.carId}`}" v-if="scope.row.carOrderState == 1"><el-dropdown-item>预定详情</el-dropdown-item></router-link>
              </div>
								<!-- 入库中的车辆才可显示 -->
              <!--<div v-if="userRoleRight">-->
								<!--<el-dropdown-item @click.native="carInStockState(scope.row)" v-if="scope.row.carStockState == 10"  >入库审核</el-dropdown-item>-->
              <!--</div>-->
                <!-- 销售出库的车辆才显示 -->
              <div v-if="userRoleRight.bookDetail">
								<router-link :to="{path: `/car/carSale/${scope.row.carId}`}"  v-if="scope.row.carStockState >= 30"><el-dropdown-item >销售详情</el-dropdown-item></router-link>
              </div>
              <div v-if="userRoleRight.printPriceTag">
                <el-dropdown-item @click.native="turnToPriceTag(scope.row.carId)" v-if="scope.row.carSaleState == 20">打印价签</el-dropdown-item>
              </div>
              <div v-if="userRoleRight.printCertificate">
                <el-dropdown-item @click.native="turnToCert(scope.row.carId)" v-if="scope.row.carAuthState == 10 && scope.row.carDetectState == 540">打印证书</el-dropdown-item>
              </div>
              <div v-if="userRoleRight.bindRFID">
                <el-dropdown-item @click.native="bindRFID(scope.row.carId,scope.row.marketId)" v-if="scope.row.carStockState < 40 && !scope.row.carRfid">绑定RFID</el-dropdown-item>
              </div>
              <div v-if="userRoleRight.changeRFID">
                <el-dropdown-item @click.native="changeRFID(scope.row.carId,scope.row.marketId)" v-if="scope.row.carStockState < 40 && scope.row.carRfid">更换RFID</el-dropdown-item>
              </div>
              <div v-if="userRoleRight.holdCar">
                <el-dropdown-item @click.native="pledge(scope.row.carId)" v-if="scope.row.carSiteState == 410 && scope.row.carPledgeState == 300" >车辆抵押</el-dropdown-item>
              </div>
              <div v-if="userRoleRight.detentionCar">
                <el-dropdown-item @click.native="rePledge(scope.row.carId)" v-if="scope.row.carPledgeState == 310" >车辆解押</el-dropdown-item>
              </div>
              <el-dropdown-item @click.native="getCarLogListFn(scope.row.carId)">操作日志</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
				</template>
			</el-table-column>
		</el-table>
		<div class="footer">
			<el-pagination
		  background

		  @size-change="handleSizeChange"
	      @current-change="handleCurrentChange"
	      :current-page="store.params.pageIndex"
	      :page-size="store.params.pageSize"
	      layout="total, sizes, prev, pager, next, jumper"
	      :total="pageTotal">
	    </el-pagination>
		</div>
		<car-in-stock-state :params="carInStockParams">
			<span slot="txt">确定同意入库吗？</span>
		</car-in-stock-state>
		<el-dialog title="操作日志" :visible.sync="dialogTableVisible" :center="true">
			<el-table :data="gridData">
				<el-table-column label="日期" width="200">
					<template slot-scope="scope">
						{{scope.row.carLogCreateTime | filterChDateForSec}}
					</template>
				</el-table-column>
				<el-table-column property="carLogInfo" label="操作" ></el-table-column>
				<el-table-column property="user.userName" label="操作人" width="200"></el-table-column>
			</el-table>
		</el-dialog>
		<el-dialog title="请上传车辆权证照片" :visible.sync="pledgeDialog"  :center="true">
			<div class="img-box" style="width:570px;margin:auto">
	            <div :class="{isHover:item.imageUrl!=''}" class="el-upload el-upload--picture-card img-input-box" v-for="(item,index) in pledgeImgList" :key="index">
	              <div class="box-shade">
	                <p class="box-img-title">{{item.imageKey | filterImageName}}</p>
	                <p class="icon-box icon-scale" @click.prevent="showPreview(item)"></p>
	                <p class="icon-box icon-delete" @click.prevent="deletePicture(index)"></p>
	              </div>
	              <p>{{item.imageKey | filterImageName}}</p>
	              <img :src="imgUrl + item.imageUrl + '.r_300xh_300'" class="img-img" onerror="javascript:this.src=''">
	              <input type="file" name="uploadFile" accept="image/*" class="img-input" @change="dealImg(item,$event)">
	            </div>
	          <el-dialog :visible.sync="pledgeImgDialog" :modal="false">
	            <img width="100%" :src="dialogImageUrl" alt="">
	          </el-dialog>

	        </div>
	        <span slot="footer" class="dialog-footer">
			    <el-button @click="pledgeDialog = false">取 消</el-button>
			    <el-button type="primary" @click="sendPledge">抵 押</el-button>
			  </span>
		</el-dialog>
  </div>
</template>

<script>
  import carInStockState from '@/components/base/baseCarInStockState'
  import '../../assets/css/car.css'
  export default {
    components: {
      carInStockState
    },
    data() {
		return {
			pledgeDialog:false,
			pledgeImgDialog:false,
			pledgeCarId:'',
			dialogImageUrl:'',
			pledgeImgList:[
				{imageUrl:'',imageKey:'pledge_vehicle_license',imageSeq:1},
				{imageUrl:'',imageKey:'pledge_registration_license',imageSeq:2},
				{imageUrl:'',imageKey:'pledge_keys',imageSeq:3},
				{imageUrl:'',imageKey:'pledge_invoice',imageSeq:4},
				{imageUrl:'',imageKey:'pledge_insurance',imageSeq:5},
				{imageUrl:'',imageKey:'pledge_duty_paid',imageSeq:6}
			],
			dialogTableVisible: false,
			gridData:[],
			carInStockParams: {
				dialogVisible: false,
				carObj: {}
			},
	        carList:null,
	        loading:true,
	        imgUrl:imageUrl,
	        showForm:false,
	        store:{
	        	carAge:'',
	        	mileage:'',
	        	retailPrice:'',
	        	marketOptions:[],
				shopOptions:[],
				brandOptions:[],
				seriesOptions:[],
				modeOptions:[],
				carTypeOptions:[],
				params:{
					pageSize:10,
					pageIndex:1,
					marketId:this.$marketId,
        	shopId:this.$shopId,
        	brandId:null,
        	seriesId:null,
        	modelId:null,
        	carStockState:null,
        	carDetectState:null,
        	carSaleState:null,
        	carOrderState:null,
        	carPledgeState:null,
        	carSiteState:null,
        	carAuthState:null,
        	carTypeId:null,
        	carEnviron:null,
        	carVin:null,
        	carRfid:null,
				},
	        },
	        pageTotal:0
		}
	},
	computed: {
		userInfo () {
			return this.$sess.get('userInfo')
		},
    userRoleRight(){
		  return this.$store.state.car.roleRight
    }
	},

    created(){
      this.getRoleRight();
      this.$store.commit('getMarketOptions',this.store)
      this.$store.commit('getBrandsOptions',this.store)
      this.$store.commit('getBaseParamOptions')
      if (this.$route.query.shopId){
        this.store.params.marketId = this.$route.query.marketId
        this.store.params.shopId = this.$route.query.shopId
      }
      this.getData()
    },
    watch:{
      "store.params.marketId" : {
        handler: function () {
          // this.store.params.shopId = ''
          this.store.shopOptions = [];
          this.$nextTick().then(() => {
            this.$store.commit("getShopOptions", this.store);
            this.$store.commit("getRegionOptions", this.store);
          });
        },
        immediate: true,
      },
      'store.params.brandId'(){
        this.store.params.seriesId = '';
        this.store.params.modelId = '';
        this.store.seriesOptions = []
        this.$nextTick().then(()=>{
          this.$store.commit('getSeriesOptions',this.store)
        })
      },
      'store.params.seriesId'(){
        this.store.params.modelId = '';
        this.store.modeOptions = []
        this.$nextTick().then(()=>{
          this.$store.commit('getModeOptions',this.store)
        })
      },
      'store.carAge'(){
        switch(this.store.carAge)
        {
          case '1':
            this.store.params.fromCarAge = 0;
            this.store.params.toCarAge = 1;
            break;
          case '2':
            this.store.params.fromCarAge = 1;
            this.store.params.toCarAge = 3;
            break;
          case '3':
            this.store.params.fromCarAge = 3;
            this.store.params.toCarAge = 5;
            break;
          case '4':
            this.store.params.fromCarAge = 5;
            this.store.params.toCarAge = 8;
            break;
          case '5':
            this.store.params.fromCarAge = 8;
            this.store.params.toCarAge = 10;
            break;
          case '6':
            this.store.params.fromCarAge = 10;
            this.store.params.toCarAge = '';
            break;
          default:
            this.store.params.fromCarAge = '';
            this.store.params.toCarAge = '';
        }
      },
      'store.mileage'(){
        switch(this.store.mileage)
        {
          case '1':
            this.store.params.fromMileage = 0;
            this.store.params.toMileage = 1;
            break;
          case '2':
            this.store.params.fromMileage = 0;
            this.store.params.toMileage = 3;
            break;
          case '3':
            this.store.params.fromMileage = 0;
            this.store.params.toMileage = 6;
            break;
          case '4':
            this.store.params.fromMileage = 0;
            this.store.params.toMileage = 10;
            break;
          case '5':
            this.store.params.fromMileage = 10;
            this.store.params.toMileage = '';
            break;
          default:
            this.store.params.fromMileage = '';
            this.store.params.toMileage = '';
        }
      },
      'store.retailPrice'(){
        switch(this.store.retailPrice)
        {
          case '1':
            this.store.params.fromRetailPrice = 0;
            this.store.params.toRetailPrice = 5;
            break;
          case '2':
            this.store.params.fromRetailPrice = 5;
            this.store.params.toRetailPrice = 10;
            break;
          case '3':
            this.store.params.fromRetailPrice = 10;
            this.store.params.toRetailPrice = 20;
            break;
          case '4':
            this.store.params.fromRetailPrice = 20;
            this.store.params.toRetailPrice = 30;
            break;
          case '5':
            this.store.params.fromRetailPrice = 30;
            this.store.params.toRetailPrice = 50;
            break;
          case '6':
            this.store.params.fromRetailPrice = 50;
            this.store.params.toRetailPrice = 100;
            break;
          case '7':
            this.store.params.fromRetailPrice = 100;
            this.store.params.toRetailPrice = '';
            break;
          default:
            this.store.params.fromRetailPrice = '';
            this.store.params.toRetailPrice = '';
        }
      },
    },
    methods:{
      getRoleRight(){
        const roleId = this.$sess.get('userInfo').roleList[0].roleId;
        this.$store.commit('getRoleRight',roleId)
      },
    	//抵押
		pledge(carId){
			this.init();
			this.pledgeCarId = carId;
			window.instance.get(this.$api.getCarImageList, {params: {
				carId: carId,
				imageViewId:1
			}}).then(res => {
				if (res.data.code == 1) {
					this.pledgeDialog = true;
					this.setImgArr(res.data.result);
				}
			})
		},
		rePledge(carId){
			window.instance.get(this.$api.setPledge, {params: {
				carId: carId,
				userId: this.userInfo.userId,
				stateValue:300,
			}}).then(res => {
				if (res.data.code == 1) {
					this.$message({
						type: 'success',
						message: '解押成功'
					})
					this.getData();
				}else{
					this.$message({
						type: 'error',
						message: res.data.msg
					})
				}
			})
		},
		init(){
			this.pledgeImgList = [
				{imageUrl:'',imageKey:'pledge_vehicle_license',imageSeq:1},
				{imageUrl:'',imageKey:'pledge_registration_license',imageSeq:2},
				{imageUrl:'',imageKey:'pledge_keys',imageSeq:3},
				{imageUrl:'',imageKey:'pledge_invoice',imageSeq:4},
				{imageUrl:'',imageKey:'pledge_insurance',imageSeq:5},
				{imageUrl:'',imageKey:'pledge_duty_paid',imageSeq:6}
			]
		},
		sendPledge(){
			window.instance.get(this.$api.setPledge, {params: {
				carId: this.pledgeCarId,
				userId: this.userInfo.userId,
				stateValue:310,
				carImageJson:JSON.stringify(this.pledgeImgList),
			}}).then(res => {
				if (res.data.code == 1) {
					this.pledgeDialog = false
					this.$message({
						type: 'success',
						message: '抵押成功'
					})
					this.getData();
				}else{
					this.$message({
						type: 'error',
						message: res.data.msg
					})
				}
			})



		},
    	showPreview(item){
			this.pledgeImgDialog = true;
			this.dialogImageUrl = this.imgUrl + item.imageUrl
		},
		deletePicture(index){
			this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '取消',
			  type: 'warning'
			}).then(() => {
			  this.pledgeImgList[index].imageUrl = '';
			  this.$message({
			    type: 'success',
			    message: '删除成功!'
			  });
			}).catch(() => {
			  this.$message({
			    type: 'info',
			    message: '已取消删除'
			  });
			});
		},
		dealImg(item,e){
			const file = e.target.files[0];
			const reader = new FileReader();
			reader.readAsDataURL(file);
			const fromData = new FormData();
			fromData.append('uploadFile', file);
			reader.onload = ()=>{
			    this.$axios.post('/controller/upload/uploadFile', fromData, {'Content-Type': 'multipart/form-data'})
			      .then(res => {
			        if (res.data.code === 0) {
			          this.$message({
			            type:'warning',
			            message:'上传失败'
			          })
			        }else{
			          this.$message({
			            type:'success',
			            message:'上传成功'
			          });
			          item.imageUrl = res.data.result.pathUrl;
			        }
			      })
			}
		},
		setImgArr(arrImg) {
	      for (var i = 0; i < this.pledgeImgList.length; i++) {
	        for (var j = 0; j < arrImg.length; j++) {
	          if (this.pledgeImgList[i].imageKey === arrImg[j].imageKey) {
	            this.pledgeImgList[i].imageUrl = arrImg[j].imageUrl;
	          }
	        }
	      }
	    },



    	//请求车辆列表
    	getData(){
    		this.loading = true;
    		this.showForm = false;
    		this.$axios.get(this.$api.getCarList,{params: this.store.params})
    		.then((res)=>{
    			this.carList = res.data.result;
    			this.loading = false;
    		})
    		this.$axios.get(this.$api.getCarNum,{params: this.store.params})
    		.then((res)=>{
    			this.pageTotal = res.data.result.total
    		})
    	},
    	searchCarList(){
			this.store.params.pageIndex = 1;
    		this.getData();
    	},
    	resetForm(){
        	this.store.params.marketId = this.$marketId
        	this.store.params.shopId = this.$shopId
        	this.store.params.brandId = null
        	this.store.params.seriesId = null
        	this.store.params.modelId = null
        	this.store.params.carStockState = null
        	this.store.params.carDetectState = null
        	this.store.params.carSaleState = null
        	this.store.params.carOrderState = null
        	this.store.params.carTypeId = null
        	this.store.params.carEnviron =  null
        	this.store.params.carPledgeState =  null
        	this.store.params.carSiteState =  null
        	this.store.params.carAuthState =  null
        	this.store.params.carVin =  null
        	this.store.params.carRfid =  null
        	this.store.params.pageIndex = 1;
        	this.getData()
      	},
      	handleSizeChange(val) {
        	this.store.params.pageSize = val;
        	this.getData()
		},
		handleCurrentChange(val) {
			this.store.params.pageIndex = val;
			this.getData()
		},
		turnToCarDetial(id){
			this.$router.push('/car/carDetial/'+id);
		},
		turnToAddCar(){
			this.$router.push('/car/carAdd');
		},
		turnToEditCar(id){
			this.$router.push('/car/carEdit/'+id);
		},
		turnToPriceTag(id){
			window.open('http://test.anpxd.com/cars/src/pricetag.html?carId='+id)
		},
		turnToCert(id){
			window.open('http://test.anpxd.com/cars/src/cert.html?carId='+id)
		},
		// 入库审核回调函数
		carInStockState (item) {
			console.log(item)
			this.carInStockParams.dialogVisible = true
			this.carInStockParams.item = item
		},
		// 查询操作日志
		getCarLogListFn (carId) {
			this.$axios.get(this.$api.getCarLogList, {params: {carId: carId}}).then(res => {
				if (res) {
					this.gridData = res.data.result
					this.dialogTableVisible = true
				}
			})
		},
		// 车辆删除
		carDelete (carId, index) {
			this.$confirm('此操作将永久删除该车辆, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
	        }).then(() => {
	          	window.instance.get(this.$api.insertCarDel, {params: {
					carId: carId,
					userId: this.userInfo.userId
				}}).then(res => {
					if (res && res.data && res.data.code == 1) {
						this.$message({
							type: 'success',
							message: '删除成功'
						})
						this.carList.splice(index, 1)
					} else {
						this.$message({
							type: 'error',
							message: '删除失败:' + res && res.data && res.data.msg
						})
					}
				})
	        }).catch(() => {
				this.$message({
				type: 'info',
				message: '已取消删除'
				});
	        });

		},
      // 申请复检
      reexamination (carId, obj) {
        this.carSaleStateFn(carId, obj, 'carDetectStatecarDetectState', 530, '申请', '是否为该车辆申请复检？', '申请')
      },
      // 车辆上架
      carSaleState20 (carId, obj) {
        this.carSaleStateFn(carId, obj, 'carSaleState', 20, '上架', '是否上架该车辆？', '上架')
      },
      // 车辆下架
      carSaleState30 (carId, obj) {
        this.carSaleStateFn(carId, obj, 'carSaleState', 30, '下架', '是否下架该车辆？', '下架')
      },
      // 状态修改
      carSaleStateFn (carId, obj, key, value, msg = "操作", title = "是否确认该操作", btn = "确定") {
        this.$confirm(title, '提示', {
          confirmButtonText: btn,
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          window.instance.get(this.$api.updateCarState, {params: {
              carId: carId,
              userId: this.userInfo.userId,
              marketId: obj.marketId,
              stateKey: key,
              stateValue: value
            }}).then(res => {
            if (res && res.data && res.data.code == 1) {
              this.$message({
                type: 'success',
                message: msg + '成功'
              })
              obj[key] = value
            } else {
              this.$message({
                type: 'error',
                message: msg + '失败:' + res && res.data && res.data.msg
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消' + msg
          });
        });
      },
      // 绑定RFID
      bindRFID(carId,marketId) {
        this.$prompt('请输入RFID', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[0-9]{2}[0-9a-f]{6}$/,
          inputErrorMessage: 'RFID格式不正确'
        }).then(({ value }) => {
          this.$confirm('车辆是否在场?', '提示', {
            confirmButtonText: '在场',
            cancelButtonText: '不在场',
            type: 'warning',
            beforeClose:(action,instance,done)=>{
              const handle = (e)=>{//处理业务逻辑，需要单独提出作为实名函数，否则事件无法移除;
                done();
                const info = e.target.innerText;
                if(action==='confirm'){
                  window.instance.get(this.$api.bindCarRfid, {params: {
                      carId: carId,
                      userId: this.userInfo.userId,
                      carRfid: value,
                      marketId: marketId
                    }}).then(res => {
                    if (res && res.data && res.data.code == 1) {
                      this.$message({
                        type: 'success',
                        message: '绑定成功'
                      });
                      this.getData()
                    }
                  });
                  window.instance.get(this.$api.updateCarState, {params: {
                      carId: carId,
                      userId: this.userInfo.userId,
                      stateKey:'carSiteState',
                      stateValue:410
                    }});
                }else{
                  if(info=='不在场'){
                    window.instance.get(this.$api.bindCarRfid, {params: {
                        carId: carId,
                        userId: this.userInfo.userId,
                        carRfid: value,
                        marketId: marketId
                      }}).then(res => {
                      if (res && res.data && res.data.code == 1) {
                        this.$message({
                          type: 'success',
                          message: '绑定成功'
                        });
                        this.getData()
                      }
                    });
                    window.instance.get(this.$api.updateCarState, {params: {
                        carId: carId,
                        userId: this.userInfo.userId,
                        stateKey:'carSiteState',
                        stateValue:400
                      }})
                  }else{
                    this.$message({
                      type: 'info',
                      message: '取消绑定'
                    });
                  }
                }
                document.removeEventListener('click',handle)//移除绑定事件
              };
              document.addEventListener('click',handle);//添加绑定事件
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消绑定'
          });
        });
      },
      changeRFID(carId,marketId) {
        this.$prompt('请输入RFID', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[0-9]{2}[0-9a-f]{6}$/,
          inputErrorMessage: 'RFID格式不正确'
        }).then(({ value }) => {
          window.instance.get(this.$api.bindCarRfid, {params: {
              carId: carId,
              userId: this.userInfo.userId,
              carRfid: value,
              marketId: marketId
            }}).then(res => {
            if (res && res.data && res.data.code == 1) {
              this.$message({
                type: 'success',
                message: '绑定成功'
              });
              this.getData()
            }
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消绑定'
          });
        });
      }

    },
    activated() {
      this.getData()
      this.$bus.$emit('showSort');
      this.$bus.$on('sort', () => {
        this.showForm = !this.showForm
      });
    },
    deactivated() {
      this.$bus.$emit('hideSort');
      this.showForm = false;
      this.$bus.$off('sort')
    }

  };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .el-dropdown-menu.el-popper a{ text-decoration: none;}

</style>
